<template>
  <div class="space-y-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between">
      <div>
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">植物列表</h2>
        <p class="mt-1 text-sm text-gray-500">管理系统中的所有植物信息</p>
      </div>
      <div class="mt-4 md:mt-0 flex space-x-3">
        <div class="relative">
          <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
            <i class="fa fa-search"></i>
          </span>
          <input 
            v-model="searchQuery"
            type="text" 
            class="pl-10 pr-4 py-2 w-full md:w-64 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom" 
            placeholder="搜索植物名称..."
          >
        </div>
        <button 
          class="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-custom"
          @click="$router.push('/plants/add')"
        >
          <i class="fa fa-plus mr-2"></i>
          <span>添加植物</span>
        </button>
      </div>
    </div>

    <div class="bg-white rounded-xl shadow-custom p-6">
      <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div class="flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-custom">
            <i class="fa fa-filter"></i>
          </button>
          <div class="relative">
            <select 
              v-model="filters.category"
              class="pl-3 pr-8 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom appearance-none bg-white"
            >
              <option value="">全部类别</option>
              <option value="乔木">乔木</option>
              <option value="灌木">灌木</option>
              <option value="草本">草本</option>
              <option value="藤本">藤本</option>
            </select>
          </div>
          <div class="relative">
            <select 
              v-model="filters.region"
              class="pl-3 pr-8 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom appearance-none bg-white"
            >
              <option value="">全部地区</option>
              <option value="华北">华北</option>
              <option value="华东">华东</option>
              <option value="华南">华南</option>
              <option value="西南">西南</option>
              <option value="西北">西北</option>
              <option value="东北">东北</option>
            </select>
          </div>
        </div>
        <div class="mt-4 md:mt-0 flex items-center space-x-2">
          <span class="text-sm text-gray-500">显示</span>
          <select 
            v-model="pageSize"
            class="pl-3 pr-8 py-1 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom appearance-none bg-white"
          >
            <option :value="10">10</option>
            <option :value="20">20</option>
            <option :value="50">50</option>
            <option :value="100">100</option>
          </select>
          <span class="text-sm text-gray-500">条/页</span>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center">
                  <input 
                    type="checkbox" 
                    class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                    v-model="selectAll"
                    @change="handleSelectAll"
                  >
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center cursor-pointer" @click="sort('name')">
                  <span>植物名称</span>
                  <i class="fa fa-sort ml-1 text-gray-400"></i>
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center cursor-pointer" @click="sort('category')">
                  <span>类别</span>
                  <i class="fa fa-sort ml-1 text-gray-400"></i>
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center cursor-pointer" @click="sort('region')">
                  <span>分布地区</span>
                  <i class="fa fa-sort ml-1 text-gray-400"></i>
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center cursor-pointer" @click="sort('componentCount')">
                  <span>成分数量</span>
                  <i class="fa fa-sort ml-1 text-gray-400"></i>
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div class="flex items-center cursor-pointer" @click="sort('updateTime')">
                  <span>更新时间</span>
                  <i class="fa fa-sort ml-1 text-gray-400"></i>
                </div>
              </th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="plant in paginatedPlants" :key="plant.id" class="hover:bg-gray-50 transition-custom">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                  v-model="selectedPlants"
                  :value="plant.id"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <img :src="plant.image" :alt="plant.name" class="h-10 w-10 rounded-full object-cover">
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ plant.name }}</div>
                    <div class="text-xs text-gray-500">{{ plant.scientificName }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getCategoryClass(plant.category)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ plant.category }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plant.region }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plant.componentCount }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plant.updateTime }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button class="text-primary hover:text-primary/80 transition-custom mr-3" @click="viewPlant(plant)">
                  <i class="fa fa-eye"></i>
                </button>
                <button class="text-gray-600 hover:text-gray-900 transition-custom mr-3" @click="editPlant(plant)">
                  <i class="fa fa-edit"></i>
                </button>
                <button class="text-danger hover:text-danger/80 transition-custom" @click="deletePlant(plant)">
                  <i class="fa fa-trash"></i>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="flex items-center justify-between mt-6">
        <div class="flex-1 flex justify-between sm:hidden">
          <button 
            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 transition-custom"
            :disabled="currentPage === 1"
            @click="currentPage--"
          >
            上一页
          </button>
          <button 
            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 transition-custom"
            :disabled="currentPage === totalPages"
            @click="currentPage++"
          >
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700">
              显示第 <span class="font-medium">{{ startIndex + 1 }}</span> 到 <span class="font-medium">{{ endIndex }}</span> 条，共 <span class="font-medium">{{ totalItems }}</span> 条记录
            </p>
          </div>
          <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
            <button 
              class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-custom"
              :disabled="currentPage === 1"
              @click="currentPage--"
            >
              <span class="sr-only">上一页</span>
              <i class="fa fa-chevron-left text-xs"></i>
            </button>
            <button 
              v-for="page in displayedPages" 
              :key="page"
              class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium transition-custom"
              :class="page === currentPage ? 'bg-primary text-white' : 'bg-white text-gray-700 hover:bg-gray-50'"
              @click="currentPage = page"
            >
              {{ page }}
            </button>
            <button 
              class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-custom"
              :disabled="currentPage === totalPages"
              @click="currentPage++"
            >
              <span class="sr-only">下一页</span>
              <i class="fa fa-chevron-right text-xs"></i>
            </button>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 模拟数据
const mockPlants = [
  {
    id: 1,
    name: '银杏',
    scientificName: 'Ginkgo biloba',
    category: '乔木',
    region: '华东',
    componentCount: 12,
    updateTime: '2024-03-15',
    image: 'https://picsum.photos/200/200?random=1'
  },
  {
    id: 2,
    name: '人参',
    scientificName: 'Panax ginseng',
    category: '草本',
    region: '东北',
    componentCount: 23,
    updateTime: '2024-03-14',
    image: 'https://picsum.photos/200/200?random=2'
  },
  {
    id: 3,
    name: '枸杞',
    scientificName: 'Lycium barbarum',
    category: '灌木',
    region: '西北',
    componentCount: 15,
    updateTime: '2024-03-13',
    image: 'https://picsum.photos/200/200?random=3'
  },
  {
    id: 4,
    name: '当归',
    scientificName: 'Angelica sinensis',
    category: '草本',
    region: '西南',
    componentCount: 18,
    updateTime: '2024-03-12',
    image: 'https://picsum.photos/200/200?random=4'
  },
  {
    id: 5,
    name: '黄芪',
    scientificName: 'Astragalus membranaceus',
    category: '草本',
    region: '华北',
    componentCount: 16,
    updateTime: '2024-03-11',
    image: 'https://picsum.photos/200/200?random=5'
  },
  {
    id: 6,
    name: '红豆杉',
    scientificName: 'Taxus chinensis',
    category: '乔木',
    region: '西南',
    componentCount: 20,
    updateTime: '2024-03-10',
    image: 'https://picsum.photos/200/200?random=6'
  },
  {
    id: 7,
    name: '金银花',
    scientificName: 'Lonicera japonica',
    category: '藤本',
    region: '华南',
    componentCount: 14,
    updateTime: '2024-03-09',
    image: 'https://picsum.photos/200/200?random=7'
  },
  {
    id: 8,
    name: '杜仲',
    scientificName: 'Eucommia ulmoides',
    category: '乔木',
    region: '华中',
    componentCount: 17,
    updateTime: '2024-03-08',
    image: 'https://picsum.photos/200/200?random=8'
  },
  {
    id: 9,
    name: '何首乌',
    scientificName: 'Polygonum multiflorum',
    category: '藤本',
    region: '华南',
    componentCount: 19,
    updateTime: '2024-03-07',
    image: 'https://picsum.photos/200/200?random=9'
  },
  {
    id: 10,
    name: '连翘',
    scientificName: 'Forsythia suspensa',
    category: '灌木',
    region: '华北',
    componentCount: 13,
    updateTime: '2024-03-06',
    image: 'https://picsum.photos/200/200?random=10'
  },
  {
    id: 11,
    name: '桔梗',
    scientificName: 'Platycodon grandiflorus',
    category: '草本',
    region: '东北',
    componentCount: 11,
    updateTime: '2024-03-05',
    image: 'https://picsum.photos/200/200?random=11'
  },
  {
    id: 12,
    name: '五味子',
    scientificName: 'Schisandra chinensis',
    category: '藤本',
    region: '东北',
    componentCount: 21,
    updateTime: '2024-03-04',
    image: 'https://picsum.photos/200/200?random=12'
  },
  {
    id: 13,
    name: '厚朴',
    scientificName: 'Magnolia officinalis',
    category: '乔木',
    region: '华中',
    componentCount: 15,
    updateTime: '2024-03-03',
    image: 'https://picsum.photos/200/200?random=13'
  },
  {
    id: 14,
    name: '白芍',
    scientificName: 'Paeonia lactiflora',
    category: '草本',
    region: '华东',
    componentCount: 16,
    updateTime: '2024-03-02',
    image: 'https://picsum.photos/200/200?random=14'
  },
  {
    id: 15,
    name: '茯苓',
    scientificName: 'Poria cocos',
    category: '真菌',
    region: '全国',
    componentCount: 12,
    updateTime: '2024-03-01',
    image: 'https://picsum.photos/200/200?random=15'
  },
  {
    id: 16,
    name: '川芎',
    scientificName: 'Ligusticum chuanxiong',
    category: '草本',
    region: '西南',
    componentCount: 14,
    updateTime: '2024-02-29',
    image: 'https://picsum.photos/200/200?random=16'
  },
  {
    id: 17,
    name: '丹参',
    scientificName: 'Salvia miltiorrhiza',
    category: '草本',
    region: '华北',
    componentCount: 18,
    updateTime: '2024-02-28',
    image: 'https://picsum.photos/200/200?random=17'
  },
  {
    id: 18,
    name: '决明子',
    scientificName: 'Cassia obtusifolia',
    category: '草本',
    region: '华南',
    componentCount: 10,
    updateTime: '2024-02-27',
    image: 'https://picsum.photos/200/200?random=18'
  },
  {
    id: 19,
    name: '山茱萸',
    scientificName: 'Cornus officinalis',
    category: '灌木',
    region: '华东',
    componentCount: 13,
    updateTime: '2024-02-26',
    image: 'https://picsum.photos/200/200?random=19'
  },
  {
    id: 20,
    name: '杜仲',
    scientificName: 'Eucommia ulmoides',
    category: '乔木',
    region: '华中',
    componentCount: 15,
    updateTime: '2024-02-25',
    image: 'https://picsum.photos/200/200?random=20'
  }
]

export default {
  name: 'PlantList',
  data() {
    return {
      plants: mockPlants,
      currentPage: 1,
      pageSize: 10,
      searchQuery: '',
      filters: {
        category: '',
        region: ''
      },
      selectedPlants: [],
      sortKey: '',
      sortOrder: 'asc' // 'asc' or 'desc'
    }
  },
  computed: {
    filteredPlants() {
      return this.plants.filter(plant => {
        const matchesSearch = this.searchQuery 
          ? plant.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
            plant.scientificName.toLowerCase().includes(this.searchQuery.toLowerCase())
          : true
        
        const matchesCategory = this.filters.category
          ? plant.category === this.filters.category
          : true
        
        const matchesRegion = this.filters.region
          ? plant.region === this.filters.region
          : true
        
        return matchesSearch && matchesCategory && matchesRegion
      })
    },
    sortedPlants() {
      if (!this.sortKey) return this.filteredPlants
      
      return [...this.filteredPlants].sort((a, b) => {
        let comparison = 0
        if (a[this.sortKey] > b[this.sortKey]) comparison = 1
        if (a[this.sortKey] < b[this.sortKey]) comparison = -1
        return this.sortOrder === 'desc' ? comparison * -1 : comparison
      })
    },
    paginatedPlants() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.sortedPlants.slice(start, end)
    },
    totalItems() {
      return this.sortedPlants.length
    },
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize)
    },
    startIndex() {
      return (this.currentPage - 1) * this.pageSize
    },
    endIndex() {
      return Math.min(this.startIndex + this.pageSize, this.totalItems)
    },
    displayedPages() {
      const pages = []
      for (let i = 1; i <= this.totalPages; i++) {
        pages.push(i)
      }
      return pages
    },
    selectAll: {
      get() {
        return this.selectedPlants.length === this.paginatedPlants.length
      },
      set(value) {
        this.selectedPlants = value 
          ? this.paginatedPlants.map(plant => plant.id)
          : []
      }
    }
  },
  methods: {
    getCategoryClass(category) {
      const classes = {
        '乔木': 'bg-blue-100 text-blue-800',
        '灌木': 'bg-green-100 text-green-800',
        '草本': 'bg-yellow-100 text-yellow-800',
        '藤本': 'bg-purple-100 text-purple-800',
        '真菌': 'bg-red-100 text-red-800'
      }
      return classes[category] || 'bg-gray-100 text-gray-800'
    },
    handleSelectAll() {
      if (this.selectAll) {
        this.selectedPlants = this.paginatedPlants.map(plant => plant.id)
      } else {
        this.selectedPlants = []
      }
    },
    sort(key) {
      if (this.sortKey === key) {
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      } else {
        this.sortKey = key
        this.sortOrder = 'asc'
      }
    },
    viewPlant(plant) {
      this.$router.push(`/plants/${plant.id}`)
    },
    editPlant(plant) {
      this.$router.push(`/plants/${plant.id}/edit`)
    },
    async deletePlant(plant) {
      if (confirm(`确定要删除 ${plant.name} 吗？`)) {
        try {
          // 这里应该调用删除 API
          this.plants = this.plants.filter(p => p.id !== plant.id)
          // 显示成功提示
        } catch (error) {
          // 显示错误提示
          console.error('删除失败:', error)
        }
      }
    }
  },
  watch: {
    pageSize() {
      this.currentPage = 1
    }
  }
}
</script>

<style scoped>
.transition-custom {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.shadow-custom {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
</style> 